import React, {Fragment} from "react";
import {Table, Button, Modal, Form, Input, Checkbox, Popconfirm, message, Select, Badge, DatePicker, Upload, Icon} from 'antd';
import {
    getNotice, addNotice, delNotice, updateNotice, getSingleNotice
} from '../../../service/api'
import './Notice.less';

import Ueditor from '../../../utils/ueditor/UEditor';
import moment from "moment/moment";
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const FormItem = Form.Item;
const Option = Select.Option;

const AuthHeaders = {
    Authorization: localStorage.getItem('user')
}

function html_decode(str) {
    let s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/<br\/>/g, "\n");
    return s;
}

class AddWaterManagementlUser extends React.Component {

    state = {
        visible: false,
        confirmLoading: false,
        fetching: false,
        peopleList:[],
        member: []
    }
    showModal = () => {
        let self = this;
        this.setState({
            visible: true
        });


    }


    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                // let limitUid;
                // for(let i in values.limitUid){
                //     if(limitUid){
                //         limitUid = limitUid+";"+values.limitUid[i].key;
                //     }else{
                //         limitUid = values.limitUid[i].key
                //     }
                // }
                // values.limitUid = limitUid;
                // values.countryId = values.countryId.key;
                values.fileNames = this.state.fileNames;
                values.fileTrueNames = this.state.fileTrueNames;
                values.content = UE.getEditor('content').getContent();
                values.f_time = values.f_time.format('YYYY-MM-DD HH:mm');
                values.status?values.status = 1:values.status = 0

                addNotice(values).then(function (data) {
                    if(data.code === 200){
                        self.props.form.resetFields();
                        self.setState({
                            visible: false,
                            confirmLoading: false,
                        })
                        self.props.retrieve();
                        self.props.close();
                        message.success("添加成功");
                    }else{
                        message.error(data.msg);
                        self.setState({
                            confirmLoading: false
                        })
                    }
                })

            }
        });

    }
    handleCancel = () => {
        this.props.form.resetFields();
        this.setState({
            visible: false,
            confirmLoading: false
        });
    }

    getRes = (info) => {
        let fileNames = [], fileTrueNames = [];
        if (info.file.status === 'done') {
            for(let i in info.fileList){
                fileNames.push(
                    info.fileList[i].response.data.fileNames[0]
                )
                fileTrueNames.push(
                    info.fileList[i].name
                )
            }
            this.setState({
                fileNames: fileNames,
                fileTrueNames: fileTrueNames
            })
        }


    }

    onChange = (value) => {
        console.log('onChange ', value);
    }

    render() {
        const { visible, confirmLoading } = this.state;
        const { getFieldDecorator } = this.props.form;

        return (
            <Fragment>
                <Button type="primary" className="fl addNew" style={{marginTop: 4}} onClick={this.showModal}>新增公告</Button>
                <Modal title="新增公告"
                       visible={visible}
                       maskClosable={false}
                       onOk={this.handleOk}
                       confirmLoading={confirmLoading}
                       onCancel={this.handleCancel}
                       okText="提交"
                       cancelText="取消"
                       width="90%"
                >

                    <Form className="modalForm">
                        <FormItem label="公告标题">
                            {getFieldDecorator('title', {
                                rules: [{ required: true, message: "标题" }],
                            })(
                                <Input placeholder="标题" />
                            )}
                        </FormItem>
                        <FormItem label="内容简介">
                            {getFieldDecorator('introduce', {
                                rules: [{ required: true, message: "内容简介" }],
                            })(
                                <textarea style={{width: "100%"}} rows={2} placeholder="内容简介"></textarea>
                            )}
                        </FormItem>
                        <div className="mb10">
                            <Ueditor id="content" height="200" />
                        </div>
                        <FormItem label="附件标题" style={{width: 300}}>
                            {getFieldDecorator('uptitle')(
                                <Input placeholder="附件标题" />
                            )}
                        </FormItem>
                        <FormItem label="附件上传">
                            <Upload action='/api/file/addFile' name='files' headers={AuthHeaders} onChange={this.getRes}>
                                <Button>
                                    <Icon type="upload" /> 上传
                                </Button>
                            </Upload>
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('status',{
                                valuePropName: 'checked',
                                initialValue: true,
                            })(
                                <Checkbox>已发布</Checkbox>
                            )}
                        </FormItem>
                        <FormItem
                            label="展示时间"
                        >
                            {getFieldDecorator('f_time', {
                                rules: [{type: 'object', required: true, message: '请选择时间'}]
                            })(
                                <DatePicker format="YYYY-MM-DD HH:mm" showTime={{ format: 'YYYY-MM-DD HH:mm' }} />
                            )}
                        </FormItem>
                    </Form>

                </Modal>
            </Fragment>
        );
    }
}

const AddWaterManagementlUserForm = Form.create()(AddWaterManagementlUser);


class ModWaterManagementUser extends React.Component {

    state = {
        visible: false,
        confirmLoading: false,
        town: {},
        fetching: false,
        info: {},
        member: [],
        fileList: []
    }

    showModal = () => {
        let self = this;
        this.setState({
            visible: true,
            id: this.props.id
        });

        getSingleNotice(this.props.id).then(function (data) {
            if(data.code === 200){
                if(data.data.thumb){
                    self.setState({
                        visible: true,
                        info: data.data,
                        fileNames: [data.data.thumb],
                        fileList: [{
                            uid: data.data.id,
                            name: data.data.thumb,
                            status: 'done',
                            url: data.data.upthumb,
                            thumbUrl: data.data.upthumb
                        }]
                    }, () => {
                        setTimeout(function () {
                            let parentTag = document.getElementById("modContent").getElementsByTagName("iframe")[0].contentWindow;
                            parentTag.document.getElementsByTagName("body")[0].innerHTML = html_decode(data.data.content);
                        },100)

                    })
                }else{
                    console.log(22)
                    self.setState({
                        visible: true,
                        info: data.data,
                        fileNames: [data.data.thumb]
                    }, () => {
                        setTimeout(function () {
                            let parentTag = document.getElementById("modContent").getElementsByTagName("iframe")[0].contentWindow;
                            parentTag.document.getElementsByTagName("body")[0].innerHTML = html_decode(data.data.content);
                        },100)

                    })
                }
            }
        })


    }

    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                values.fileNames = this.state.fileNames;
                values.fileTrueNames = this.state.fileTrueNames;
                values.content = UE.getEditor('modContent').getContent();
                values.f_time = values.f_time.format('YYYY-MM-DD HH:mm');
                values.status?values.status = 1:values.status = 0;
                updateNotice(self.state.id, values).then(function (data) {
                    if(data.code === 200){
                        self.setState({
                            visible: false,
                            confirmLoading: false,
                        })
                        self.props.retrieve();
                        message.success("成功");
                    }else{
                        message.error(data.msg);
                        self.setState({
                            confirmLoading: false
                        })
                    }
                })

            }
        });

    }
    handleCancel = () => {
        this.props.form.resetFields();
        this.setState({
            visible: false,
            confirmLoading: false,
        });
    }

    getRes = (info) => {
        let fileNames = [], fileTrueNames = [];
        if (info.file.status === 'done') {
            for(let i in info.fileList){
                fileNames.push(
                    info.fileList[i].response.data.fileNames[0]
                )
                fileTrueNames.push(
                    info.fileList[i].name
                )
            }
            this.setState({
                fileNames: fileNames,
                fileTrueNames: fileTrueNames
            })
        }


    }

    render() {
        const { visible, confirmLoading } = this.state;
        const { getFieldDecorator } = this.props.form;
        return (
            <Fragment>
                <Button type="primary" className="mr10" onClick={this.showModal}>修改</Button>
            <Modal title="修改公告"
                   visible={visible}
                   maskClosable={false}
                   onOk={this.handleOk}
                   confirmLoading={confirmLoading}
                   onCancel={this.handleCancel}
                   okText="确定"
                   cancelText="取消"
                   width="90%"
            >

                <Form className="modalForm">

                    <FormItem label="公告标题">
                        {getFieldDecorator('title', {
                            rules: [{ required: true, message: "标题" }],
                            initialValue: this.state.info.title
                        })(
                            <Input placeholder="标题" />
                        )}
                    </FormItem>
                    <FormItem label="内容简介">
                        {getFieldDecorator('introduce', {
                            rules: [{ required: true, message: "内容简介" }],
                            initialValue: this.state.info.introduce
                        })(
                            <textarea style={{width: "100%"}} rows={2} placeholder="内容简介"></textarea>
                        )}
                    </FormItem>
                    <div className="mb10">
                        <Ueditor id="modContent" height="200" />
                    </div>

                    <FormItem label="附件标题" style={{width: 300}}>
                        {getFieldDecorator('uptitle',{
                            initialValue: this.state.info.uptitle
                        })(
                            <Input placeholder="附件标题" />
                        )}
                    </FormItem>
                    <FormItem label="附件上传">
                        <Upload action='/api/file/addFile' headers={AuthHeaders} fileList={this.state.fileList} name='files' onChange={this.getRes}>
                            <Button>
                                <Icon type="upload" /> 上传
                            </Button>
                        </Upload>
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator('status',{
                            valuePropName: 'checked',
                            initialValue: this.state.info.status,
                        })(
                            <Checkbox>已发布</Checkbox>
                        )}
                    </FormItem>
                    <FormItem
                        label="展示时间"
                    >
                        {getFieldDecorator('f_time', {
                            rules: [{type: 'object', required: true, message: '请选择时间'}],
                            initialValue: moment(this.state.info.ftimeStr, 'YYYY-MM-DD HH:mm')
                        })(
                            <DatePicker format="YYYY-MM-DD HH:mm" showTime={{ format: 'YYYY-MM-DD HH:mm' }} />
                        )}
                    </FormItem>
                </Form>

            </Modal>
            </Fragment>

        );
    }
}

const ModWaterManagementUserForm = Form.create()(ModWaterManagementUser);

class Notice extends React.Component{

    state = {
        permissions: JSON.parse(localStorage.permissions),
        data: [],
        limit: 20,
        offset: 0,
        showData: [],
        modVisible: false,
        loading: true,
        modId: "",
        height: document.body.clientHeight - 230,
        pagination: {pageSize: 20},
    }

    componentDidMount() {
        this.getData();
    }

    getData = () => {
        let self = this;
        self.setState({loading: true});
        const pagination = { ...this.state.pagination };
        getNotice({
            limit: this.state.limit,
            offset: this.state.offset
        }).then(function (data) {
            pagination.total = data.data.total;
            if(data.code === 200){
                self.setState({data: data.data.rows, showData: data.data.rows, loading: false, modVisible:false, pagination})
            }
        })

    }

    del = (id) => {
        let self = this;
        if(id){
            delNotice(id).then(function (data) {
                if(JSON.parse(data).code === 200){
                    self.getData();
                    message.success("删除成功");
                }
            })
        }

    }

    mod = (id, key) => {
        this.setState({modId :id, modVisible: true, modKey: key});
    }


    turnModalDown = () => {
        this.setState({modVisible: false})
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            this.setState({loading: true})
            if (!err) {
                console.log('Received values of form: ', values);
                //levelName, fcode, town
                let nowData = [];

                for(let i in this.state.data){
                    if((values.title == ""?true:this.state.data[i].title.indexOf(values.title) > -1)  && this.state.data[i] != undefined){
                        nowData.push(this.state.data[i])
                    }

                }
                this.setState({showData: nowData,loading: false})
            }
        });
    }

    render(){
        const { getFieldDecorator } = this.props.form;
        let data = [];
        if(this.state.showData.length){
            for(let i in this.state.showData){
                data.push({
                    key: i,
                    id: this.state.showData[i].id,
                    title: this.state.showData[i].title,
                    ftimeStr: this.state.showData[i].ftimeStr,
                    status: this.state.data[i].status == 1?<Fragment><Badge status="success" />已发布</Fragment>:<Fragment><Badge status="warning" />未发布</Fragment>
                })
            }
        }

        let columnsRoot = [
            {
                dataIndex: 'id',
                title: 'id',
                width: 60
            },
            {
                dataIndex: 'title',
                title: '标题',
                width: 220
            },
            {
                dataIndex: 'ftimeStr',
                title: '展示时间',
                width: 150
            },
            {
                dataIndex: 'status',
                title: '状态',
                width: 80
            },

            {
                title: '操作',
                width: 150,
                render: (record) => (
                    <div className="tableOperation">
                        {this.state.permissions["sys:notice:update"]?<ModWaterManagementUserForm retrieve={this.getData} id={record.id.toString()} />: true}

                        {this.state.permissions["sys:notice:delete"]?
                            <Popconfirm placement="leftBottom" title={`确定删除此条公告吗?`} id={record.id.toString()} onConfirm={() => this.del(record.id)} okText="确定" cancelText="取消">
                                <Button type="danger" id={record.userId} ghost>删除</Button>
                            </Popconfirm>:true}
                    </div>
                )
            }
        ]

        return(
            <div className="mt10 ml10">
                <div className="clearfix tableFilter">
                <Form className="fl searchForm" layout="inline" onSubmit={this.handleSubmit}>
                    <FormItem>
                        {getFieldDecorator('title',{
                            initialValue: ""
                        })(
                            <Input placeholder="标题" />
                        )}
                    </FormItem>

                    <FormItem>
                        <Button
                            type="primary"
                            htmlType="submit"
                        >
                            搜索
                        </Button>
                    </FormItem>
                </Form>
                {this.state.permissions["sys:notice:add"]?<AddWaterManagementlUserForm retrieve={this.getData} close={this.turnModalDown} />:true}
                </div>
                <Table className="mt10 scrollTable" columns={columnsRoot} dataSource={data} loading={this.state.loading} pagination={this.state.pagination} scroll={{y: this.state.height }} bordered />
            </div>
        )
    }

}
const NoticeForm = Form.create()(Notice);
export default NoticeForm;